import urllib.request
import json
from datetime import datetime

def get_school_codes():
    url = 'https://static-data.gaokao.cn/www/2.0/school/school_code.json?a=www.gaokao.cn'
    headers = {
        'sec-ch-ua-platform': '""',
        'Referer': 'https://www.gaokao.cn/',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15',
        'Accept': 'application/json, text/plain, */*',
        'sec-ch-ua': '""',
        'sec-ch-ua-mobile': '?0'
    }
    
    # 创建请求对象
    req = urllib.request.Request(url, headers=headers)
    
    # 发送请求并获取响应
    with urllib.request.urlopen(req) as response:
        response_data = response.read().decode('utf-8')
        
    # 解析JSON响应
    return json.loads(response_data)

def save_to_file(data, filename="学校代码数据.txt"):
    # 先保存一份原始JSON数据以便检查格式
    with open('学校代码数据_原始.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    # 打开文件准备写入
    with open(filename, 'w', encoding='utf-8') as f:
        # 写入文件头部信息
        f.write(f"获取时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
        f.write("==== 学校代码列表 ====\n\n")
        
        # 检查数据结构
        if isinstance(data, dict):
            # 如果是字典，检查是否有data字段
            if 'data' in data and isinstance(data['data'], list):
                schools = data['data']
                for school in schools:
                    if isinstance(school, dict):
                        for key, value in school.items():
                            f.write(f"{key}: {value}\n")
                    else:
                        f.write(f"{school}\n")
                    f.write("--------------------------------------------------\n")
            else:
                # 直接遍历顶层字典
                for key, value in data.items():
                    f.write(f"{key}: {value}\n")
                f.write("--------------------------------------------------\n")
        elif isinstance(data, list):
            # 如果是列表，直接遍历
            for item in data:
                if isinstance(item, dict):
                    for key, value in item.items():
                        f.write(f"{key}: {value}\n")
                else:
                    f.write(f"{item}\n")
                f.write("--------------------------------------------------\n")
        else:
            # 如果是其他类型，直接写入
            f.write(f"{data}\n")

def main():
    print("开始获取学校代码数据...")
    
    try:
        result = get_school_codes()
        print(f"数据类型: {type(result)}")
        
        # 简单显示数据结构
        if isinstance(result, dict):
            print(f"字典键: {list(result.keys())}")
        elif isinstance(result, list):
            print(f"列表长度: {len(result)}")
            if len(result) > 0:
                print(f"第一个元素类型: {type(result[0])}")
        
        filename = "学校代码数据.txt"
        save_to_file(result, filename)
        
        print(f"数据获取完成，已保存到 {filename}")
        print(f"原始数据已保存到 学校代码数据_原始.json")
        
    except Exception as e:
        print(f"获取数据时出错: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
